package MyThread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock锁使用 获取锁的时候，一定得释放锁，若不释放，则其他线程可能一直为阻塞 lock为（重量级锁）
 * 而synchronized不需要释放只需要争抢资源
 *
 */
public class MyLock {
    private static volatile Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        MyLock myLock = new MyLock();
        myLock.print1();
        myLock.print2();
    }

    public void print1() {
        new Thread(() -> {
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"获取锁成功！");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                lock.unlock();
            }
        },"t1").start();
    }

    public void print2() {
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"获取锁成功！1");
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"获取锁成功！2");
        },"t2").start();
    }
}
